<template>
  <div class="user-avatar-dropdown tabr">
    <Dropdown @on-click="handleClick">
      <Badge :dot="!!messageUnreadCount">
        <Avatar icon="ios-person"/>
        <span class="fontName colorFFF ml10 mr10">
          <span style="display: inline-block">
            <opendata type="userName" :openid="name" style="vertical-align: middle;"></opendata>
          </span>
        </span>
      </Badge>
      <Icon :size="14" type="ios-arrow-down"></Icon>
      <DropdownMenu slot="list">
        <!-- <DropdownItem name="message">
          消息中心<Badge
            style="margin-left: 10px"
            :count="messageUnreadCount"
          ></Badge>
        </DropdownItem> -->
<!--        <DropdownItem name="changepwd">修改密码</DropdownItem>-->
        <DropdownItem name="logout" v-if="ifhuanjing">退出登录</DropdownItem>
      </DropdownMenu>
    </Dropdown>

    <base-modal
      ref="editPassword"
      :loading="modalBtnLoading"
      v-model="editPassword"
      @closeM="cancel"
      @closeBt="cancel"
      @submitBt="okSave"
      titleText="修改密码"
      :styles="{width: '412px',borderRadius: '6px'}"
    >
      <Form
        ref="formCustom"
        :model="formCustom"
        :rules="ruleCustom"
        :label-width="95"
      >
        <template>
          <div>
            <FormItem label="旧密码" prop="pwd">
              <Input type="password" v-model="formCustom.pwd"></Input>
            </FormItem>
            <FormItem label="输入新密码" prop="newPwd">
              <Input type="password" v-model="formCustom.newPwd"></Input>
            </FormItem>
            <FormItem label="请重新输入" prop="passwdCheck">
              <Input type="password" v-model="formCustom.passwdCheck"></Input>
            </FormItem>
          </div>
        </template>
      </Form>
    </base-modal>

    <!-- 退出提示 -->
    <Delete
      ref="delt"
      :content="'是否退出登录？'"
      :isVisble="false"
      @modalConfirmTrue="modalConfirmTrue"
    />
  </div>
</template>
<script>
import "./user.less";
import {mapActions, mapState} from "vuex";
import BaseModal from "_c/base-modal"

export default {
  components: {
    BaseModal,
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.formCustom.passwdCheck !== "") {
          // 对第二个密码框单独验证
          this.$refs.formCustom.validateField("passwdCheck");
        }
        callback();
      }
    };
    const validatePassCheck = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.formCustom.newPwd) {
        callback(new Error("两个输入的密码不匹配!"));
      } else {
        callback();
      }
    };
    const validateAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("原密码不能是空的"));
      }

      /*this.APIS.oldPassword({pwd: value})
        .then((res) => {*/
          callback();
          this.$Message.success("验证成功");
          // return  callback(new Error('验证失败，请重新输入原密码'));
        /*})
        .catch((err) => {
          this.$Message.error("旧密码错误，请重新输入");
          return callback(new Error("旧密码错误，请重新输入"));
        });*/
    };

    return {
      ifhuanjing: false,
      name: "", //用户名
      editPassword: false,
      modalBtnLoading: false,
      formCustom: {
        newPwd: "",
        passwdCheck: "",
        pwd: "",
      },
      pwdlist: {},
      ruleCustom: {
        // 表单验证
        newPwd: [{validator: validatePass, trigger: "blur"}],
        passwdCheck: [{validator: validatePassCheck, trigger: "blur"}],
        pwd: [{validator: validateAge, trigger: "blur"}],
      },
      namelist: "",
    };
  },
  name: "User",
  props: {
    userAvatar: {
      type: String,
      default: "",
    },
    messageUnreadCount: {
      type: Number,
      default: 0,
    },
  },
  created() {
    this.getLocal();
    if (this.envjudge() === "com-wx-pc") {
      this.ifhuanjing = false;
    } else {
      this.ifhuanjing = true;
    }
  },
  computed: {},
  methods: {
    envjudge() {
      var isMobile = window.navigator.userAgent.match(
        /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
      ); // 是否手机端
      var isWx = /micromessenger/i.test(navigator.userAgent); // 是否微信
      var isComWx = /wxwork/i.test(navigator.userAgent); // 是否企业微信
      if (isComWx && isMobile) {
        //手机端企业微信
        return "com-wx-mobile";
      } else if (isComWx && !isMobile) {
        //PC端企业微信
        return "com-wx-pc";
      } else if (isWx && isMobile) {
        // 手机端微信
        return "wx-mobile";
      } else if (isWx && !isMobile) {
        // PC端微信
        return "wx-pc";
      } else {
        // PC端
        return "other";
      }
    },
    //
    getLocal() {
      let localItem = JSON.parse(window.localStorage.getItem("myData"));
      this.name = localItem.userName;
      this.namelist = [{name: localItem.userName}];
    },
    ...mapActions(["handleLogOut"]),
    logout() {
      this.$refs.delt.instance();
    },
    message() {
      this.$router.push({
        name: "message_page",
      });
    },
    changepwd() {
      this.modalBtnLoading = false;
      this.editPassword = true;
    },
    handleClick(name) {
      switch (name) {
        case "logout":
          this.logout();
          break;
        case "message":
          this.message();
          break;
        case "changepwd":
          this.changepwd();
          break;
      }
    },
    // 确定退出
    async modalConfirmTrue() {
      this.$store.commit('removeToken')
      await this.handleLogOut().then(() => {
        // 清空路由配置并回到登录页面
        localStorage.clear();
        this.$store.commit("setShowRouter", []);
        if (process.env.NODE_ENV === "prerelease") {
          window.location.href = "https://preshoufei.yzxsaas.com/pc";
        } else if (process.env.NODE_ENV === "production") {
          window.location.href = "https://preshoufei.yzxsaas.com/pc";
        } else {
          this.$router.push({
            name: "login",
          });
          this.$router.go(0)
        }
      });
    },

    cancel() {
      // 关闭弹窗事件
      this.modalBtnLoading = false;
      this.editPassword = false;
      this.$refs.formCustom.resetFields();
    },
    okSave() {
      this.$refs.formCustom.validate((valid) => {
        if (valid) {
          this.modalBtnLoading = true;
          let datas = {newPwd: this.formCustom.newPwd};
          // this.APIS.newPassword(datas).then((res) => {
              this.modalBtnLoading = false;
            // if (res.code === 20000) {
              this.editPassword = false;
              this.$Message.success("修改成功");
              this.handleLogOut().then(() => {
                this.$router.push({
                  name: "login",
                });
              });
            // }
          // });
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
/deep/ .ivu-avatar{
  background: #fff;
  color: #ccc;
}

.tabr {
  /deep/ .ivu-dropdown-menu {
    margin-bottom: 0px;
  }

  /deep/ .ivu-select-dropdown {
    top: 45px !important;
  }
}

.titleqh {
  text-align: center;
  font-size: 16px;
  font-weight: 600;
  color: #333333;
  padding-top: 24px;
  padding-bottom: 15px;
}

.cont {
  display: flex;
  flex-direction: column;
  width: 100%;
  align-items: center;
  justify-content: space-evenly;
}

.contents {
  width: 210px;
  height: 87px;
  background: #ffffff;
  border: 1px solid #cccccc;
  border-radius: 5px;
  cursor: pointer;
}

.heade {
  height: 60px;
  text-align: center;
  line-height: 60px;

  span {
    font-size: 22px;
    font-weight: bold;
    color: #0085FF;
  }
}

.foote {
  width: 100%;
  height: 25px;
  line-height: 25px;
  text-align: center;
  background: #E7F1F9;
  border-radius: 0 0 4px 4px;

  span {
    font-size: 12px;
    font-weight: 400;
    color: #717171;
    line-height: 16px;
  }
}

.contents-other {
  .heade {
    height: 100%;
    line-height: 87px;
  }

  .foote {
    display: none;
  }
}
</style>
